package com.jhs.kjs.model.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jhs.kjs.handler.exception.AldangMessegeException;

/**
 * 첨부파일 다운 받기. 서버에 있는 파일을 사용자에게 보내는 클래스
 * 
 * @author SSaMKJ
 * 
 */
public class FileDownloadManager {
	private static final String TEMP_FOLDER_NAME_FOR_FIND_ABSOLUTE_PATH = "TEMPFOLDERNAMEFORFINDABSOLUTEPATH";
	private HttpServletRequest request;
	private HttpServletResponse response;

	private InputStream in = null;
	private OutputStream os = null;
	private File file;
	private String realName = "";
	private StringBuilder sb = new StringBuilder();
	/**
	 * 파라미터 세팅이 끝나면 시작은 doDownload()
	 * 
	 * @param request
	 * @param response
	 */
	public FileDownloadManager(HttpServletRequest request,
			HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}

	/**
	 * 파일 세팅
	 * 
	 * @param file
	 * @throws IOException
	 */
	public void setFile(File file) throws IOException {
		this.file = file;

	}

	public void doDownload() throws FileNotFoundException,
			UnsupportedEncodingException, IOException {
		log("first absolutePath try");
		log(file.getAbsolutePath());
		log("before file.exists() = "+file.exists());
		checkFile();
		log("after file.exists() = "+file.exists());
		try {
			in = new FileInputStream(file);
			request.setAttribute("inputStream", in);
			request.setAttribute("fileLength", file.length());
			request.setAttribute("fileName", getFileName());

			String client = "";

			client = request.getHeader("User-Agent");
			response.reset();
			if (client.indexOf("MSIE 5.5") != -1) {
				response.setHeader("Content-Type",
						"doesn/matter; charset=euc-kr");
				response.setHeader(
						"Content-Disposition",
						"filename="
								+ new String(getFileName().getBytes("euc-kr"),
										"8859_1"));
			} else {
				response.setHeader("Content-Type",
						"application/octet-stream; charset=euc-kr");
				response.setHeader("Content-Disposition",
						"attachment; filename="
								+ new String(getFileName().getBytes("euc-kr"),
										"8859_1"));
			}// else
			response.setHeader("Content-Transfer-Encoding", "binary;");
			response.setHeader("Content-Length", "" + file.length());
			response.setHeader("Pragma", "no-cache;");
			response.setHeader("Expires", "-1;");

			os = response.getOutputStream();
			byte b[] = new byte[4096];
			int leng = 0;
			while ((leng = in.read(b)) > 0) {
				os.write(b, 0, leng);
			}// while

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				os.flush();
				os.close();
			}
			if (os != null) {
				os.close();
			}
			if (in != null) {
				in.close();
			}
		}
	}

	private String getFileName() {
		String fn =  this.realName == null ? this.file.getName() : this.realName;
		sb.append("<br/>").append("getFilename = "+fn);
		return fn;
	}

	/**
	 * 
	 * @param file
	 * @param fileName
	 *            - 다운로드 될 실제 이름
	 * @throws IOException
	 */
	public void setFile(File file, String fileName) throws IOException {
		setFile(file);
		this.realName = fileName;
	}

	/**
	 * 
	 * @param filePath
	 * @param fileName
	 * @throws IOException
	 */
	public void setFile(String filePath, String fileName) throws IOException {
		File file = new File(filePath, fileName);

		checkFile();
		setFile(file);
	}

	private void checkFile() {
		if (!file.exists()) {
			// sb.append("<br/>").append("여기서는 못 찾음.");
			// sb.append("<br/>").append(file.getAbsolutePath());
			String tempPath = file.getAbsolutePath().replaceAll(file.getName(), "");

			File t = new File(TEMP_FOLDER_NAME_FOR_FIND_ABSOLUTE_PATH);
			// sb.append("<br/>").append(t.getAbsolutePath());
			file = new File(t.getAbsolutePath().replaceAll(
					TEMP_FOLDER_NAME_FOR_FIND_ABSOLUTE_PATH, "")
					+"www"+File.separator+ tempPath, file.getName());
			sb.append("<br/>").append(file.getAbsolutePath());

		}
		sb.append("<br/>").append("1111111111111111111111111");
		sb.append("<br/>").append(file.getAbsolutePath());
		if (!file.exists()) {
			sb.append("<br/>").append("여기서는 못 찾음.");
			sb.append("<br/>").append(file.getAbsolutePath());
			String tempPath = getTestPath();
			file = new File(tempPath, file.getName());
		}
		sb.append("<br/>").append("2222222222222222222222");
		sb.append("<br/>").append(file.getAbsolutePath());
		if (!file.exists()) {

			file = new File("test");
			sb.append("<br/>").append(file.getAbsolutePath());

//			throw new AldangMessegeException(
//					"파일을 못 찾았음. 만약 로컬 테스트용이라면 테스트 패쓰를 잘 맞춰보도록! 리얼서버라면 개발자에게...");
		}
	}

	/**
	 * 
	 * @param filePath
	 * @param fileName
	 * @param realName
	 *            - 다운로드 될 때의 실제 이름
	 * @throws IOException
	 */
	public void setFile(String filePath, String fileName, String realName)
			throws IOException {
		setFile(filePath, fileName);
		this.realName = realName;
	}

	private String getTestPath() {
		String tempPath = "c:" + File.separator + "project" + File.separator
				+ "Aldang" + File.separator + "workspace" + File.separator
				+ "Aldang" + File.separator + "src" + File.separator + "main"
				+ File.separator + "customerResource" + File.separator + "";
		return tempPath;
	}
	private void log(String s){
		sb.append("<br/>").append(s).append("<br/>");
	}
	public String getLog(){
		return sb.toString();
	}
}
